package com.hk.yajin.function.messages;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.androidadvance.topsnackbar.TSnackbar;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hk.developmentlib.baseben.NewWorkBean;
import com.hk.developmentlib.callback.HttpCallBack;
import com.hk.developmentlib.utills.FastjsonUtils;
import com.hk.developmentlib.utills.UiUtil;
import com.hk.yajin.R;
import com.hk.yajin.base.BaseFragment;
import com.hk.yajin.function.members.activity.LoginAndRegisterActivity;
import com.hk.yajin.manager.UserInfoManager;
import com.hk.yajin.model.Attach;
import com.hk.yajin.model.Message;
import com.hk.yajin.utills.HttpRequestUtils;
import com.hk.yajin.utills.MessageHelper;
import com.hk.yajin.utills.SQLMessageEven;
import com.hk.yajin.utills.url.UrlConstants;
import com.hk.yajin.view.PhotoZoomActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by 伦哥哥 on 2017/6/25.
 */

public class MenuMessageFragment extends BaseFragment {
    private Toolbar toolbar;
    protected RecyclerView mRecyclerView;
    protected MessageListQuickAdapter mQuickAdapter;
    protected SwipeRefreshLayout swipe_container;
    protected List<Message> dataList = new ArrayList<>();
    /*请求标记*/
    private int maxId;
    private int minId;
    /*悬浮层*/
    private TextView tv_float_day;
    private TextView tv_float_ymd;
    private LinearLayout lly_ymd;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void getNewDataFromWeb() {
        if (isNetWorkConnect()) {
            showLoadingView();
            if (dataList != null && dataList.size() > 0) {
                maxId = dataList.get(0).getLog_id();
            }
            Map<String, Object> reqParam = UserInfoManager.getUserKeyMapIfLogin();
            if (maxId != 0) {
                reqParam.put("max_log_id", maxId);
            }
            HttpRequestUtils.post(false, UrlConstants.FUNCTION_VIEW_MESSAGE_LIST, reqParam, false, new HttpCallBack() {
                @Override
                public void onSucced(String data) {
                    swipe_container.setRefreshing(false);
                    hideLoadingView();
                    handleNewData(FastjsonUtils.getBeanList(data, Message.class));
                    mQuickAdapter.setEnableLoadMore(true);
                }

                @Override
                public void onBadHttp(String tip) {
                    swipe_container.setRefreshing(false);
                    hideLoadingView();
                    showShortToast(tip);
                    mQuickAdapter.loadMoreFail();
                }

                @Override
                public void onErrorCode(NewWorkBean bean) {
                    swipe_container.setRefreshing(false);
                    hideLoadingView();
                    showShortToast(bean.getMsg());
                    mQuickAdapter.loadMoreFail();
                }
            });
        } else {
            swipe_container.setRefreshing(false);
        }
    }


    private void getOldDataFromWeb() {
        if (isNetWorkConnect()) {
            Map<String, Object> reqParam = UserInfoManager.getUserKeyMapIfLogin();
            if (minId != 0) {
                reqParam.put("min_log_id", minId);
            }
            HttpRequestUtils.post(false, UrlConstants.FUNCTION_VIEW_MESSAGE_LIST, reqParam, false, new HttpCallBack() {
                @Override
                public void onSucced(String data) {
                    handleOldData(FastjsonUtils.getBeanList(data, Message.class));
                }

                @Override
                public void onBadHttp(String tip) {
                    showShortToast(tip);
                    mQuickAdapter.loadMoreFail();
                }

                @Override
                public void onErrorCode(NewWorkBean bean) {
                    showShortToast(bean.getMsg());
                    mQuickAdapter.loadMoreFail();
                }
            });
        } else {
            UiUtil.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mQuickAdapter.loadMoreFail();
                }
            }, 500);

        }

    }

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container) {
        mContentView = inflater.inflate(R.layout.fragment_menu_message, container, false);
        initToolBar();
        initSwipeView();
        initAdapter();
        initRecyclerView();
        tv_float_day = (TextView) mContentView.findViewById(R.id.tv_float_day);
        tv_float_ymd = (TextView) mContentView.findViewById(R.id.tv_float_ymd);
        lly_ymd = (LinearLayout) mContentView.findViewById(R.id.lly_ymd);
        return mContentView;
    }


    protected void initSwipeView() {
        swipe_container = (SwipeRefreshLayout) mContentView.findViewById(R.id.swipe_container);
        swipe_container.setEnabled(true);
        swipe_container.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                showTopTip();
                getNewDataFromWeb();
            }
        });
    }

    public void initAdapter() {
        mQuickAdapter = new MessageListQuickAdapter(dataList, getActivity());
        //mQuickAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_LEFT);
        mQuickAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.iv_attach:
                        handleAttach(dataList.get(position).getMail_attachs());
                        break;
                }
            }
        });
        mQuickAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                getOldMessage();
            }
        }, mRecyclerView);

    }

    protected void initRecyclerView() {
        mRecyclerView = (RecyclerView) mContentView.findViewById(R.id.rv_list);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mRecyclerView.setAdapter(mQuickAdapter);
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                View item = recyclerView.findChildViewUnder(recyclerView.getMeasuredWidth(), 10);
                if (item != null) {
                    TextView tv_ymd = (TextView) item.findViewById(R.id.tv_ymd);
                    TextView tv_day = (TextView) item.findViewById(R.id.tv_day);
                    if (tv_ymd != null && tv_day != null) {
                        lly_ymd.setVisibility(View.VISIBLE);
                        tv_float_ymd.setText(tv_ymd.getText().toString());
                        tv_float_day.setText(tv_day.getText().toString());
                    }
                }

            }
        });
    }

    private void showTopTip() {
        TSnackbar snackbar = TSnackbar.make(toolbar, getString(R.string.message_buy_tip), TSnackbar.LENGTH_LONG);
        snackbar.setActionTextColor(UiUtil.getColor(R.color.white));
        View snackbarView = snackbar.getView();
        snackbarView.setBackgroundColor(UiUtil.getColor(R.color.blue_2476fe));
        TextView textView = (TextView) snackbarView.findViewById(com.androidadvance.topsnackbar.R.id.snackbar_text);
        textView.setGravity(Gravity.CENTER);
        textView.setTextColor(Color.WHITE);
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (UserInfoManager.getInstance().isLogin()) {
                    startActivity(BuyMessageActivity.class);
                } else {
                    startActivity(LoginAndRegisterActivity.class);
                }

            }
        });
        snackbar.show();
    }

    private void initToolBar() {
        toolbar = (Toolbar) mContentView.findViewById(R.id.toolbar);
        toolbar.setBackgroundColor(UiUtil.getColor(R.color.white));
        toolbar.setTitle("");
        TextView textView = (TextView) mContentView.findViewById(R.id.tv_title);
        textView.setText(UiUtil.getString(R.string.title_message));
        textView.setTextColor(UiUtil.getColor(R.color.black_282828));
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (!isCreated) {
            isCreated = true;
            initDataFromSql();
        }
    }

    private void handleAttach(List<Attach> attaches) {
        if (attaches != null && attaches.size() > 0) {
            List<String> imageStrings = new ArrayList<>();
            for (Attach attach : attaches) {
                if (attach.getAttach_type().equals("png")) {
                    imageStrings.add(attach.getAttach_path());
                }
            }
            Intent photoZoomIntent = new Intent(getActivity(), PhotoZoomActivity.class);
            photoZoomIntent.putExtra("imageUrls", imageStrings.toArray(new String[imageStrings.size()]));
            startActivity(photoZoomIntent);
        }
    }


    private void initDataFromSql() {
        showLoadingView();
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<Message> temList = MessageHelper.getInstance().getInitMessage(20);
                EventBus.getDefault().post(new SQLMessageEven(SQLMessageEven.InitData, temList));
            }
        }).start();

//        List<Message> temList = MessageHelper.getInstance().getInitMessage(num);
//        if (temList != null && temList.size() > 0) {
//            dataList.clear();
//            dataList.addAll(temList);
//            mQuickAdapter.notifyDataSetChanged();
//        }
    }

    private void getOldDataFromSql(final int minId) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<Message> temList = MessageHelper.getInstance().getOldMessageByMinId(minId, 20);
                EventBus.getDefault().post(new SQLMessageEven(SQLMessageEven.LoadMore, temList));
            }
        }).start();

//        List<Message> temList = MessageHelper.getInstance().getOldMessageByMinId(minId, 20);
//        if (temList != null && temList.size() > 0) {
//            dataList.addAll(temList);
//            mQuickAdapter.loadMoreComplete();
//            mQuickAdapter.notifyDataSetChanged();
//        }
    }


    private void getOldMessage() {
        minId = dataList.get(dataList.size() - 1).getLog_id();
        new Thread(new Runnable() {
            @Override
            public void run() {
                boolean hasMoreMessage = MessageHelper.getInstance().hasMoreOldMessage(minId);
                EventBus.getDefault().post(new SQLMessageEven(SQLMessageEven.QueryDataCount, hasMoreMessage));
            }
        }).start();
//        if () {
//            getOldDataFromSql(minId);
//        } else {
//            getOldDataFromWeb();
//        }
    }


    private void handleOldData(List<Message> temList) {
        if (temList != null && temList.size() > 0) {
            MessageHelper.getInstance().saveMessages(temList);
            dataList.addAll(temList);
            mQuickAdapter.loadMoreComplete();
            mQuickAdapter.notifyDataSetChanged();
        } else {
            mQuickAdapter.loadMoreEnd();
        }
    }

    private void handleNewData(List<Message> temList) {
        if (temList != null && temList.size() > 0) {
            MessageHelper.getInstance().saveMessages(temList);
            dataList.addAll(0, temList);
            mQuickAdapter.notifyDataSetChanged();
        } else {
            if (dataList == null || dataList.size() == 0) {
                showDefaultView_NO_DTTA();
            }
        }
    }

    @Override
    public void defaultViewClick(int tag) {
        hideDefaultView();
        getNewDataFromWeb();
    }

    @Override
    public void onResume() {
        super.onResume();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetMessageFromSql(SQLMessageEven event) {
        switch (event.getEvenType()) {
            case SQLMessageEven.InitData:
                hideLoadingView();
                if (event.getSqlDatas() != null && event.getSqlDatas().size() > 0) {
                    dataList.clear();
                    dataList.addAll(event.getSqlDatas());
                    mQuickAdapter.notifyDataSetChanged();
                }
                getNewDataFromWeb();
                break;
            case SQLMessageEven.LoadMore:
                if (event.getSqlDatas() != null && event.getSqlDatas().size() > 0) {
                    dataList.addAll(event.getSqlDatas());
                    mQuickAdapter.loadMoreComplete();
                    mQuickAdapter.notifyDataSetChanged();
                }
                break;
            case SQLMessageEven.QueryDataCount:
                if (event.isHasMoreMessage()) {
                    getOldDataFromSql(minId);
                } else {
                    getOldDataFromWeb();
                }
                break;
        }
    }
}
